package com.xidian.zhiancloud.service.equipFacility;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xidian.zhiancloud.dao.*;
import com.xidian.zhiancloud.dao.syset.PositionMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.PositionList;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.equipFacility.DefendPlanExecuteQO;
import com.xidian.zhiancloud.qo.equipFacility.DefendPlanMakeQO;
import com.xidian.zhiancloud.qo.equipFacility.DefendPlanRegisterQO;
import com.xidian.zhiancloud.vo.equipFacility.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @ClassName DefendPlanExecService
 * @Description 维护计划执行
 * @Author Halo
 **/
@Service
public class DefendPlanExecService {

    @Autowired
    private DefendPlanMakeMapper defendPlanMakeMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private DefendObjectMapper defendObjectMapper;

    @Autowired
    private EqFacMngMapper eqFacMngMapper;

    @Autowired
    private DefendPlanRegisterMapper defendPlanRegisterMapper;

    @Autowired
    private DefendRegisterService defendRegisterService;

    @Autowired
    private DefendRegisterMapper defendRegisterMapper;

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private DeviceTypeMapper deviceTypeMapper;

    @Autowired
    private DefendPlanExecMapper defendPlanExecMapper;

    @Autowired
    private DefendStandardMapper defendStandardMapper;

    /**
     * 检修计划执行--列表查询
     * @param defendPlanMakeQO
     * @param currentUserId
     * @return
     */
    public IPage<DefendPlanMakeVO> getListByQO(DefendPlanMakeQO defendPlanMakeQO,Long currentUserId) {

        Page<DefendPlanMakeVO> page = new Page<>(defendPlanMakeQO.getCurrent(), defendPlanMakeQO.getSize());

        //排序
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);

        IPage<DefendPlanMakeVO> list= defendPlanMakeMapper.selectByQO(page, defendPlanMakeQO);

        List<DefendPlanMakeVO> new_list = new ArrayList<>();

        for (DefendPlanMakeVO record : list.getRecords()) {

            if(record.getStatus() == 0){
                continue;
            }

            //检修人是否包含当前用户
            LambdaQueryWrapper<DefendObject> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(DefendObject::getDefendPlanMakeId,record.getId());
            List<DefendObject> defendObjects = defendObjectMapper.selectList(queryWrapper);

            for (DefendObject defendObject : defendObjects) {
                String defender = defendObject.getDefender();
                long[] array = Arrays.stream(defender.split(",")).mapToLong(Long::parseLong).toArray();
                int  i = 0;
                for(;i< array.length;i++){
                    if(currentUserId == array[i]){
                        new_list.add(record);
                        break;
                    }
                }

                if(i < array.length){
                    break;
                }
            }
        }

        list.setRecords(new_list);
        return list;
    }

    /**
     * 检修计划执行---执行
     * @param currentUserId
     * @param defendPlanExecuteQO
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public IPage<DefendObjectVO> execute(Long currentUserId, DefendPlanExecuteQO defendPlanExecuteQO){

        Page<DefendObjectVO> page = new Page<>(defendPlanExecuteQO.getCurrent(),defendPlanExecuteQO.getSize());
        IPage<DefendObjectVO> list = defendObjectMapper.selectEqFacByQO(page,defendPlanExecuteQO);

        list.getRecords().forEach(obj -> {

            //管辖部门名称
            Organization organization = organizationMapper.selectById(obj.getMngCtrDeptId());
            obj.setDepartmentName(organization == null ? "该部门不存在" : organization.getName());

            //区域位置
            PositionList position = positionMapper.selectById(obj.getPosition());
            obj.setPositionName(position == null ? "该区域位置不存在" : position.getName());

            //维护人姓名
            SysUser sysUser = sysUserMapper.selectById(currentUserId);
            obj.setDefenderName(sysUser == null ? "该用户不存在" : sysUser.getName());
        });

        return list;
    }

    /**
     * 查看设备信息和维护项
     * @param planId 维护计划id
     * @param eqFacMngId 设备设施id
     * @return
     */
    public DefendPlanEqFacMngVO getEqFacMngMsg(Long planId,Long eqFacMngId){
        DefendPlanEqFacMngVO vo = new DefendPlanEqFacMngVO();

        //查询设备信息
        EqFacMng eqFacMng = eqFacMngMapper.selectById(eqFacMngId);
        if(eqFacMng == null){
            throw new CustomizeException(GeneralResponseEnums.UPLOAD_FAILED);
        }
        BeanUtils.copyProperties(eqFacMng,vo);

        Organization organization = organizationMapper.selectById(eqFacMng.getMngCtrDeptId());
        vo.setDepartmentName(organization == null ? "该部门不存在" : organization.getName());

        PositionList position = positionMapper.selectById(eqFacMng.getPosition());
        vo.setPositionName(position == null ? "该区域位置不存在" : position.getName());

        DeviceType deviceType = deviceTypeMapper.selectById(eqFacMng.getDeviceTypeId());
        vo.setDeviceTypeName(deviceType == null ? "该类型不存在" : deviceType.getName());

        //查询维护项
        LambdaQueryWrapper<DefendStandard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DefendStandard::getEqFacId,eqFacMngId);
        List<DefendStandard> standards = defendStandardMapper.selectList(queryWrapper);

        List<DefendStandardStatusVO> list = new ArrayList<>();

        //判断检修项是否维护
        for (DefendStandard obj : standards) {
            DefendStandardStatusVO defendStandardStatusVO = new DefendStandardStatusVO();
            BeanUtils.copyProperties(obj,defendStandardStatusVO);

            LambdaQueryWrapper<DefendPlanRegister> query = new LambdaQueryWrapper<>();
            query.eq(DefendPlanRegister::getPlanId,planId);
            query.eq(DefendPlanRegister::getEqFacId,eqFacMngId);
            query.eq(DefendPlanRegister::getDefendStandardId,obj.getId());
            List<DefendPlanRegister> registerList = defendPlanRegisterMapper.selectList(query);
            if(registerList == null || registerList.size() == 0){
                defendStandardStatusVO.setIsDefended(0);
            }else{
                defendStandardStatusVO.setIsDefended(1);
            }


            list.add(defendStandardStatusVO);
        }

        vo.setStandardList(list);
        return vo;
    }

    /**
     * 提交
     * @param id 维护计划id
     * @param currentUserId  执行人id
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean submit(Long id,Long currentUserId){

        //添加维护计划执行
        DefendPlanExec defendPlanExec = new DefendPlanExec();
        defendPlanExec.setDefendPlanMakeId(id);
        defendPlanExec.setExecutor(currentUserId);

        int insert = defendPlanExecMapper.insert(defendPlanExec);
        if(insert == 0){
            throw new CustomizeException(GeneralResponseEnums.SUBMIT_FAILED);
        }

        //判断当前维护计划是否执行完毕   通过判断当前维护计划需要维护设备的所有维护项之和与维护计划登记的条数是否相等
        //查询当前计划需要维护的所有设备
        LambdaQueryWrapper<DefendObject> queryObject = new LambdaQueryWrapper<>();
        queryObject.eq(DefendObject::getDefendPlanMakeId,id);
        List<DefendObject> defendObjects = defendObjectMapper.selectList(queryObject);

        int count = 0;
        for (DefendObject object : defendObjects) {
            //查询所有检修设备的检修项之和
            LambdaQueryWrapper<DefendStandard> queryStandard = new LambdaQueryWrapper<>();
            queryStandard.eq(DefendStandard::getEqFacId,object.getEqFacId());
            List<DefendStandard> list = defendStandardMapper.selectList(queryStandard);
            count += list.size();
        }

        //查询当前检修计划登记的记录
        LambdaQueryWrapper<DefendPlanRegister> queryRegister = new LambdaQueryWrapper<>();
        queryRegister.eq(DefendPlanRegister::getPlanId,id);
        List<DefendPlanRegister> registerList = defendPlanRegisterMapper.selectList(queryRegister);

        //判断计划登记条数与所有需要检修的检修项是否相等
        if(count != registerList.size()){
            throw new CustomizeException(GeneralResponseEnums.INCOMPLETE_EXECUTION);
        }

        //修改计划状态
        DefendPlanMake defendPlanMake = defendPlanMakeMapper.selectById(id);
        defendPlanMake.setStatus(2);
        int ret = defendPlanMakeMapper.updateById(defendPlanMake);
        if(ret == 0){
            throw new CustomizeException(GeneralResponseEnums.SUBMIT_FAILED);
        }

        return true;
    }

    /**
     * 维护计划执行--执行--维护
     * @param defenderId  维护人id
     * @param defendPlanRegisterQO
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean defend(Long defenderId, DefendPlanRegisterQO defendPlanRegisterQO){

        DefendStandard defendStandard = defendStandardMapper.selectById(defendPlanRegisterQO.getDefendStandardId());
        if(defendStandard == null){
            throw new CustomizeException(GeneralResponseEnums.OPERATE_DAILED);
        }

        DefendRegister defendRegister = new DefendRegister();
        BeanUtils.copyProperties(defendPlanRegisterQO,defendRegister);
        //添加 维护登记
        defendRegister.setCreator(defenderId);
        defendRegister.setCreateTime(new Date());
        defendRegister.setDefenderIds(defenderId+",");
        defendRegister.setDefendTime(new Date());
        defendRegister.setStatus(1);
        defendRegister.setDefendCont(defendStandard.getDefendCont());
        defendRegister.setProtectStep(defendStandard.getProtectStep());
        defendRegister.setDefendTypeId(defendStandard.getDefendTypeId());

        int insert = defendRegisterMapper.insert(defendRegister);
        if(insert == 0){
            throw new CustomizeException(GeneralResponseEnums.OPERATE_DAILED);
        }

        //保存维护登记id
        DefendPlanRegister defendPlanRegister = new DefendPlanRegister();
        defendPlanRegister.setEqFacId(defendPlanRegisterQO.getDeviceId());
        defendPlanRegister.setPlanId(defendPlanRegisterQO.getPlanId());
        defendPlanRegister.setRegisterId(defendRegister.getId());
        defendPlanRegister.setDefendStandardId(defendPlanRegisterQO.getDefendStandardId());

        int ret = defendPlanRegisterMapper.insert(defendPlanRegister);
        if(ret == 0){
            throw new CustomizeException(GeneralResponseEnums.OPERATE_DAILED);
        }
        return true;
    }

    /**
     * 维护项维护之后【编辑】可修改
     * @param defendRegister
     * @return
     */
    public Boolean updateById(DefendRegister defendRegister){

        if(defendRegister == null){
            throw new CustomizeException(GeneralResponseEnums.UPDATE_FAILED);
        }

        int ret = defendRegisterMapper.updateById(defendRegister);
        if(ret == 0){
            throw new CustomizeException(GeneralResponseEnums.UPDATE_FAILED);
        }

        return true;
    }

    /**
     * 执行之后---查看
     * @param defendPlanRegisterQO 维护计划id  设备设施id
     * @return
     */
    public EqFacAndRegisterVO lookOver(DefendPlanRegisterQO defendPlanRegisterQO){

        EqFacAndRegisterVO vo = new EqFacAndRegisterVO();

        /*//根据维护计划id和设备设施id，查找维护登记id
        LambdaQueryWrapper<DefendPlanRegister> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DefendPlanRegister::getEqFacId,defendPlanRegisterQO.getDeviceId());
        queryWrapper.eq(DefendPlanRegister::getPlanId,defendPlanRegisterQO.getPlanId());
        List<DefendPlanRegister> list = defendPlanRegisterMapper.selectList(queryWrapper);

        if(list.isEmpty()){
            throw new CustomizeException(GeneralResponseEnums.UPLOAD_FAILED);
        }

        DefendPlanRegister defendPlanRegister = list.get(0);

        //查找  维护登记信息
        DefendRegister defendRegister = defendRegisterMapper.selectById(defendPlanRegister.getRegisterId());
        if(defendPlanRegister == null){
            throw new CustomizeException(GeneralResponseEnums.UPLOAD_FAILED);
        }
        vo.setDefendRegister(defendRegister);*/

        //查找设备设施信息
        EqFacMng eqFacMng = eqFacMngMapper.selectById(defendPlanRegisterQO.getDeviceId());
        if(eqFacMng == null){
            throw new CustomizeException(GeneralResponseEnums.UPLOAD_FAILED);
        }
        String mngment = eqFacMng.getMngment();
        String name = "";
        long[] array = Arrays.stream(mngment.split(",")).mapToLong(Long::parseLong).toArray();
        for (long id : array) {
            SysUser sysUser = sysUserMapper.selectById(id);
            if(sysUser != null){
                name += sysUser.getName() + ",";
            }
        }
        eqFacMng.setMngment(name);
        vo.setEqFacMng(eqFacMng);

        Organization organization = organizationMapper.selectById(eqFacMng.getMngCtrDeptId());
        vo.setMngCtrDeptName(organization == null ? "该部门不存在" : organization.getName());

        PositionList positionList = positionMapper.selectById(eqFacMng.getPosition());
        vo.setPositionName(positionList == null ? "该区域不存在" : positionList.getName());

        DeviceType deviceType = deviceTypeMapper.selectById(eqFacMng.getDeviceTypeId());
        vo.setDeviceTypeName(deviceType == null ? "该设备类型不存在" : deviceType.getName());

        //查询维护项信息
        DefendStandard defendStandard = defendStandardMapper.selectById(defendPlanRegisterQO.getDefendStandardId());
        vo.setDefendStandard(defendStandard);

        return vo;
    }


    /**
     * 检修之后查看维护项维护信息
     * @param defendPlanRegisterQO
     * @return
     */
    public DefendRegister getRegister(DefendPlanRegisterQO defendPlanRegisterQO){

        //查询维护登记id
        LambdaQueryWrapper<DefendPlanRegister> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DefendPlanRegister::getDefendStandardId,defendPlanRegisterQO.getDefendStandardId());
        queryWrapper.eq(DefendPlanRegister::getEqFacId,defendPlanRegisterQO.getDeviceId());
        queryWrapper.eq(DefendPlanRegister::getPlanId,defendPlanRegisterQO.getPlanId());
        List<DefendPlanRegister> list = defendPlanRegisterMapper.selectList(queryWrapper);

        DefendPlanRegister register = list.get(0);

        //查询维护登记信息
        DefendRegister defendRegister = defendRegisterMapper.selectById(register.getRegisterId());

        return defendRegister;
    }
}
